﻿IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'RegistroOTSave')
	BEGIN
		DROP  Procedure  RegistroOTSave
	END
GO


CREATE PROCEDURE RegistroOTSave 	
	(	
		@empresaId AS INT,
		@numeroOT AS VARCHAR(30),		
		@fechaInicial AS DATETIME,		
		@clienteId AS VARCHAR(12) = NULL,
		@articuloId AS VARCHAR(13) = NULL,
		@unidades AS DECIMAL(10,2)  = NULL,
		@manoObraIndirecta AS DECIMAL(10,2)  = NULL
	)	
AS
BEGIN	
	SET NOCOUNT ON

	DECLARE @id AS INT
	
	SELECT @id = id 
	FROM Lit_OrdenTrabajo 
	WHERE EmpresaId = @empresaId
	  AND NumeroOT = @numeroOT

	
	IF @id IS NOT NULL
	BEGIN
	
		-- Remueve todos registros asociados para recrearlos despues en los otros SPs
		DELETE FROM Lit_OTDetalle	WHERE OTId = @id
		DELETE FROM Lit_OTMaterial	WHERE OTId = @id
		DELETE FROM Lit_OTGasto		WHERE OTId = @id
		
	
		UPDATE Lit_OrdenTrabajo
		SET		FechaInicial = @fechaInicial,
				ClienteId = @clienteId,	
				ArticuloId = @articuloId,
				Unidades = @unidades,	
				ManoObraIndirecta = @manoObraIndirecta
		WHERE Id = @id
	END
	ELSE
	BEGIN		
		INSERT INTO Lit_OrdenTrabajo 
			(EmpresaId, FechaInicial, NumeroOT, ClienteId, ArticuloId, Unidades, ManoObraIndirecta, Estado)		
		VALUES 
			(@empresaId, @fechaInicial, @numeroOT, @clienteId, @articuloId, @unidades, @manoObraIndirecta, 'A')
		
		SELECT @id = Scope_identity()
	END	

	SELECT @id
		
	SET NOCOUNT OFF
END
GO  